#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include "Log.hpp"
#include "Comment.hpp"
#include "InetAddr.hpp"
using namespace LogModule;

void Usage(std::string s)
{
    std::cerr << "Please use: " << s << " ip prot" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(TCPCLIENT_ERR);
    }

    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        LOG(LogLevel::ERROR) << "socket error";
        exit(SOCK_ERR);
    }

    // 绑定信息，但由OS自动绑定，无需我们自己绑定

    // 申请建立连接请求
    uint16_t prot = stoi(argv[2]);
    InetAddr addr(argv[1], prot);
    int n = connect(sockfd, addr.Getaddr(), addr.Len());
    if (n < 0)
    {
        LOG(LogLevel::ERROR) << "connect error";
        exit(CONN_ERR);
    }

    while (true)
    {
        cout << "Please Enter@ ";
        string str;
        cin >> str;
        // 向服务器发送信息
        write(sockfd, str.c_str(), str.size());

        // 接收服务器的信息
        char buff[1024];
        int n = read(sockfd, buff, sizeof(buff));
        if (n > 0)
        {
            buff[n] = 0;
            cout << "Eoch: " << buff << endl;
        }
    }
}